import argparse
import numpy as np
import os
import pickle
import platform
import sys
from pathlib import Path
import PIL.Image as Image

import torch
from torchvision.utils import draw_segmentation_masks
import torchvision.transforms as transforms

FILE = Path(__file__).resolve()
ROOT = FILE.parents[1]  # YOLO root directory
if str(ROOT) not in sys.path:
    sys.path.append(str(ROOT))  # add ROOT to PATH
ROOT = Path(os.path.relpath(ROOT, Path.cwd()))  # relative

from models.common import DetectMultiBackend
from models.yolo import SegmentationModel
from utils.caption.caption_utils import bert_tokenizer, create_caption_and_mask, create_src_mask
from utils.dataloaders import IMG_FORMATS, VID_FORMATS, LoadImages, LoadScreenshots, LoadStreams
from utils.general import (LOGGER, Profile, check_file, check_img_size, check_imshow, check_requirements, colorstr, cv2,
                           increment_path, non_max_suppression, print_args, scale_boxes, scale_segments,
                           strip_optimizer, xyxy2xywh)
from utils.model_utils import find_layer
from utils.plots import Annotator, colors, save_one_box
from utils.segment.general import masks2segments, process_mask
from utils.torch_utils import select_device, smart_inference_mode

VIDEO_CAPTION_SETTINGS = {
    # ratio of top padding and bottom padding is 3 : 7
    'high': {
        'fontScale': 3,  # height of font size is 66
        'thickness': 5,
        'width_pad': 5,
        'height_pad': 50,  # 15 : 35
        'org': (5, 81),  # 15 + 66 = 81
    },
    'medium': {
        'fontScale': 2,  # height of font size is 45
        'thickness': 4,
        'width_pad': 5,
        'height_pad': 40,  # 12 : 28
        'org': (5, 56),  # 12 + 45 = 56
    },
    'low': {
        'fontScale': 1,  # height of font size is 24
        'thickness': 3,
        'width_pad': 5,
        'height_pad': 30,  # 9 : 21
        'org': (5, 33),  # 9 + 24 = 33
    },
}

@smart_inference_mode()
def run(
    weights=ROOT / 'yolo-cap.pt',  # model.pt path(s)
    source=ROOT / 'data/images',  # file/dir/URL/glob/screen/0(webcam)
    data=ROOT / 'data/coco128.yaml',  # dataset.yaml path
    imgsz=(640, 640),  # inference size (height, width)
    conf_thres=0.25,  # confidence threshold
    iou_thres=0.45,  # NMS IOU threshold
    max_det=1000,  # maximum detections per image
    device='',  # cuda device, i.e. 0 or 0,1,2,3 or cpu
    view_img=False,  # show results
    save_txt=False,  # save results to *.txt
    save_conf=False,  # save confidences in --save-txt labels
    save_crop=False,  # save cropped prediction boxes
    nosave=False,  # do not save images/videos
    classes=None,  # filter by class: --class 0, or --class 0 2 3
    agnostic_nms=False,  # class-agnostic NMS
    augment=False,  # augmented inference
    visualize=False,  # visualize features
    update=False,  # update all models
    project=ROOT / 'runs/predict-seg',  # save results to project/name
    name='exp',  # save results to project/name
    exist_ok=False,  # existing project/name ok, do not increment
    line_thickness=3,  # bounding box thickness (pixels)
    hide_labels=False,  # hide labels
    hide_conf=False,  # hide confidences
    half=False,  # use FP16 half-precision inference
    dnn=False,  # use OpenCV DNN for ONNX inference
    vid_stride=1,  # video frame-rate stride
    retina_masks=False,
    export_mask = False,
    color_map = ROOT / 'data/color_map.pickle',  # for semantic segmentation
):
    source = str(source)
    save_img = not nosave and not source.endswith('.txt')  # save inference images
    is_file = Path(source).suffix[1:] in (IMG_FORMATS + VID_FORMATS)
    is_url = source.lower().startswith(('rtsp://', 'rtmp://', 'http://', 'https://'))
    webcam = source.isnumeric() or source.endswith('.txt') or (is_url and not is_file)
    screenshot = source.lower().startswith('screen')
    if is_url and is_file:
        source = check_file(source)  # download

    # Directories
    save_dir = increment_path(Path(project) / name, exist_ok=exist_ok)  # increment run
    (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True)  # make dir

    # Load model
    device = select_device(device)
    model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data, fp16=half)
    stride, names, pt = model.stride, model.names, model.pt
    imgsz = check_img_size(imgsz, s=stride)  # check image size

    # Semantic Segmentation
    if export_mask:
        with open(color_map, 'rb') as f:
            color_map = pickle.load(f)

    model_yaml = model.model.yaml  # if isinstance(model.model, SegmentationModel)
    num_instance = model_yaml['nc']

    # Caption
    caption_file = Path(save_dir / 'captions.txt')
    if ('caption_tokenizer' in model.hyp) and ('custom' == model.hyp['caption_tokenizer']):
        tokenizer = bert_tokenizer(
            model = model.hyp['caption_tokenizer'],
            vocab = model.hyp['caption_vocab_path'],
            do_lower = True,
        )
    else:
        tokenizer = bert_tokenizer(do_lower = True)

    model_key = ('model.model' if not isinstance(model.model, SegmentationModel) else 'model.model.model') if not hasattr(model, 'module') else 'model.module.model'
    caption_idx = find_layer(eval(model_key), ['Caption', 'Grit'])

    # Dataloader
    bs = 1  # batch_size
    if webcam:
        view_img = check_imshow(warn=True)
        dataset = LoadStreams(source, img_size=imgsz, stride=stride, auto=pt, vid_stride=vid_stride)
        bs = len(dataset)
    elif screenshot:
        dataset = LoadScreenshots(source, img_size=imgsz, stride=stride, auto=pt)
    else:
        dataset = LoadImages(source, img_size=imgsz, stride=stride, auto=pt, vid_stride=vid_stride)
    vid_path, vid_writer = [None] * bs, [None] * bs

    # Run inference
    model.warmup(imgsz=(1 if pt else bs, 3, *imgsz), caption_idx = caption_idx)  # warmup
    seen, windows, dt = 0, [], (Profile(), Profile(), Profile())
    for path, im, im0s, vid_cap, s in dataset:
        if caption_idx is not None:
            # set params
            _, src_mask = create_src_mask(torch.unsqueeze(torch.from_numpy(im), 0))
            # cap, cap_mask = create_caption_and_mask(128)
            # eval(model_key)[caption_idx].set_params(src_mask, cap, cap_mask, auto_forward = True, beam_size = 1)
            eval(model_key)[caption_idx].set_params(src_mask.to(model.device), None, None, use_beam_search = True, beam_size = 5, out_size = 1, return_probs = False)

        with dt[0]:
            im = torch.from_numpy(im).to(model.device)
            im = im.half() if model.fp16 else im.float()  # uint8 to fp16/32
            im /= 255  # 0 - 255 to 0.0 - 1.0
            if len(im.shape) == 3:
                im = im[None]  # expand for batch dim

        # Inference
        with dt[1]:
            visualize = increment_path(save_dir / Path(path).stem, mkdir=True) if visualize else False
            output = model(im, augment=augment, visualize=visualize)
            pred, out = output['detect'][:2]
            proto = out[2]
            psemasks = out[3]

            pred_caption = output['captions']

        # NMS
        with dt[2]:
            pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det, nm=32)

        # Second-stage classifier (optional)
        # pred = utils.general.apply_classifier(pred, classifier_model, im, im0s)

        # Process predictions
        for i, (det, psemask, pred_caption) in enumerate(zip(pred, psemasks, pred_caption)):  # per image
            seen += 1
            if webcam:  # batch_size >= 1
                p, im0, frame = path[i], im0s[i].copy(), dataset.count
                s += f'{i}: '
            else:
                p, im0, frame = path, im0s.copy(), getattr(dataset, 'frame', 0)

            p = Path(p)  # to Path
            save_path = str(save_dir / p.name)  # im.jpg
            txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}')  # im.txt
            s += '%gx%g ' % im.shape[2:]  # print string
            imc = im0.copy() if save_crop else im0  # for save_crop
            annotator = Annotator(im0, line_width=line_thickness, example=str(names))

            # Caption
            caption = tokenizer.get_decoded_caption(pred_caption[0], skip_special_tokens = True)
            print(caption)
            with open(caption_file, 'a') as f:
                f.write(save_path + "\n" + caption + "\n")

            if len(det):
                masks = process_mask(proto[i], det[:, 6:], det[:, :4], im.shape[2:], upsample=True)  # HWC
                det[:, :4] = scale_boxes(im.shape[2:], det[:, :4], im0.shape).round()  # rescale boxes to im0 size

                # Segments
                if save_txt:
                    segments = reversed(masks2segments(masks))
                    segments = [scale_segments(im.shape[2:], x, im0.shape, normalize=True) for x in segments]

                # Print results
                for c in det[:, 5].unique():
                    n = (det[:, 5] == c).sum()  # detections per class
                    s += f"{n} {names[int(c)]}{'s' * (n > 1)}, "  # add to string

                # Mask plotting
                annotator.masks(masks,
                                colors=[colors(x, True) for x in det[:, 5]],
                                im_gpu=None if retina_masks else im[i])

                # Write results
                for j, (*xyxy, conf, cls) in enumerate(reversed(det[:, :6])):
                    if save_txt:  # Write to file
                        segj = segments[j].reshape(-1)  # (n,2) to (n*2)
                        line = (cls, *segj, conf) if save_conf else (cls, *segj)  # label format
                        with open(f'{txt_path}.txt', 'a') as f:
                            f.write(('%g ' * len(line)).rstrip() % line + '\n')

                    if save_img or save_crop or view_img:  # Add bbox to image
                        c = int(cls)  # integer class
                        label = None if hide_labels else (names[c] if hide_conf else f'{names[c]} {conf:.2f}')
                        annotator.box_label(xyxy, label, color=colors(c, True))
                        # annotator.draw.polygon(segments[j], outline=colors(c, True), width=3)
                    if save_crop:
                        save_one_box(xyxy, imc, file=save_dir / 'crops' / names[c] / f'{p.stem}.jpg', BGR=True)

            # Stream results
            im0 = annotator.result()
            if view_img:
                if platform.system() == 'Linux' and p not in windows:
                    windows.append(p)
                    cv2.namedWindow(str(p), cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO)  # allow window resize (Linux)
                    cv2.resizeWindow(str(p), im0.shape[1], im0.shape[0])
                cv2.imshow(str(p), im0)
                if cv2.waitKey(1) == ord('q'):  # 1 millisecond
                    exit()

            # Save results (image with detections)
            fps = 30
            h, w, ch = im0.shape
            if vid_cap:  # video
                fps = vid_cap.get(cv2.CAP_PROP_FPS)
                w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
                h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
            # else:  # stream
            #     fps, w, h = 30, im0.shape[1], im0.shape[0]

            if save_img:
                if dataset.mode == 'image':
                    cv2.imwrite(save_path, im0)
                else:  # 'video' or 'stream'
                    if vid_path[i] != save_path:  # new video
                        vid_path[i] = save_path
                        if isinstance(vid_writer[i], cv2.VideoWriter):
                            vid_writer[i].release()  # release previous video writer

                        save_path = str(Path(save_path).with_suffix('.mp4'))  # force *.mp4 suffix on results videos
                        vid_writer[i] = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))

                    settings = VIDEO_CAPTION_SETTINGS['high'] if 2000 < w else \
                                (VIDEO_CAPTION_SETTINGS['low'] if 1000 >= w else VIDEO_CAPTION_SETTINGS['medium'])

                    (text_width, text_height) = cv2.getTextSize(str(caption), cv2.FONT_HERSHEY_SIMPLEX, settings['fontScale'], settings['thickness'])[0]
                    text_width += settings['width_pad']
                    text_height += settings['height_pad']
                    text_mask = np.zeros((text_height, text_width, ch), dtype = np.uint8)
                    text_mask += 255
                    text_mask = cv2.putText(text_mask, str(caption), settings['org'], cv2.FONT_HERSHEY_SIMPLEX, settings['fontScale'], (0, 0, 255), settings['thickness'], cv2.LINE_AA)

                    if text_width > w:
                        text_mask = cv2.resize(text_mask, (w, text_height))
                        text_width = w

                    im0[-text_height:, :text_width, :] = text_mask

                    vid_writer[i].write(im0)
                    # cv2.imwrite(str(save_path + '_debug.png'), im0)

            if export_mask:
                # Semantic segmentation
                file_name = save_path
                for img_format in IMG_FORMATS:
                    file_name = file_name.replace(f'.{img_format}', f'_mask.{img_format}')

                (oh, ow, _) = im0.shape

                _, ic, ih, iw = im.shape
                psemask = torch.nn.functional.interpolate(psemask[None, :], size = (ih, iw), mode = 'bilinear', align_corners = False)
                psemask = psemask.squeeze()
                ch, mask_h, mask_w = psemask.shape

                semantic_masks = torch.flatten(psemask, start_dim = 1).permute(1, 0) # (h x w) x class
                max_idx = semantic_masks.argmax(1)
                output_img_mask = torch.zeros(semantic_masks.shape).scatter(1, max_idx.cpu().unsqueeze (1), 1.0) # one hot: (h x w) x class
                output_img_mask = torch.reshape(output_img_mask.permute(1, 0), (ch, mask_h, mask_w)) # class x h x w

                # resize
                h_ratio = ih / oh
                w_ratio = iw / ow

                if len(det):
                    output_img_mask = torch.cat((masks.to(device), output_img_mask.to(device)), 0)

                if h_ratio == w_ratio:
                    output_img_mask = torch.nn.functional.interpolate(output_img_mask[None, :], size = (oh, ow), mode = 'bilinear', align_corners = False)
                else:
                    transform = transforms.CenterCrop((oh, ow))

                    if (1 != h_ratio) and (1 != w_ratio):
                        h_new = oh if (h_ratio < w_ratio) else int(mask_h / w_ratio)
                        w_new = ow if (h_ratio > w_ratio) else int(mask_w / h_ratio)
                        output_img_mask = torch.nn.functional.interpolate(output_img_mask[None, :], size = (h_new, w_new), mode = 'bilinear', align_corners = False)

                    output_img_mask = transform(output_img_mask)
                output_img_mask = torch.squeeze(output_img_mask)

                if len(det):
                    masks = output_img_mask[: len(det)]
                    output_img_mask = output_img_mask[len(det) :]

                output_img = draw_segmentation_masks(
                    # image = torch.nn.functional.interpolate((img_back[b])[None, :], size = (h_new, w_new), mode = 'bilinear', align_corners = False).to(dtype = torch.uint8).cpu(),
                    image = torch.zeros((ic, oh, ow)).to(dtype = torch.uint8),
                    masks = torch.squeeze(output_img_mask).to(dtype = torch.bool).cpu(),
                    alpha = 1,
                    colors = color_map[1 :],
                )

                if save_img:
                    if 'image' == dataset.mode:
                        cv2.imwrite(
                            file_name,
                            torch.permute(output_img, (1, 2, 0)).numpy()
                        )
                    # else:  # 'video' or 'stream' # TODO: video & stream

                # Panoptic segmentation
                panoptic_name = save_path
                for img_format in IMG_FORMATS:
                    panoptic_name = panoptic_name.replace(f'.{img_format}', f'_panoptic_mask.{img_format}')
                output_img_mask = output_img_mask[num_instance :]  # only stuff
                output_colors = color_map[num_instance + 1 :]  # remove 0 (unlabeled) and number of instances

                if len(det):
                    instance_colors = []
                    shift_colors = {}

                    instance_cls = det[:, 5]
                    for cls in instance_cls:
                        id = int(cls)  + 1
                        instance_color = list(color_map[id])
                        if id not in shift_colors:
                            shift_num = 1
                            shift_colors[id] = 1
                        else:
                            shift_num = shift_colors[id]
                            shift_colors[id] += 1

                            pos_num = shift_num % 2
                            pos_idx = 0 if ((0 == pos_num) and (0 != (id % 3))) \
                                else (2 if ((1 == pos_num) and (2 != (id % 3))) else 1)
                            increase_num = ((shift_num // 2) + 1) * 3

                            instance_color[pos_idx] = (instance_color[pos_idx] + increase_num) % 255

                        instance_colors.append(tuple(instance_color))

                    output_img_mask = torch.cat((masks.cpu(), output_img_mask.cpu()), 0)
                    output_colors = instance_colors + output_colors

                panoptic_mask = np.zeros((oh, ow, 3), dtype = np.uint8)
                for output_mask, output_color in zip(output_img_mask, output_colors):
                    if 0 != torch.sum(output_mask):
                        panoptic_mask[1 == output_mask] = output_color

                if save_img:
                    if 'image' == dataset.mode:
                        Image.fromarray(panoptic_mask).save(panoptic_name)
                    # else:  # 'video' or 'stream' # TODO: video & stream

        # Print time (inference-only)
        LOGGER.info(f"{s}{'' if len(det) else '(no detections), '}{dt[1].dt * 1E3:.1f}ms")

    # Print results
    t = tuple(x.t / seen * 1E3 for x in dt)  # speeds per image
    LOGGER.info(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {(1, 3, *imgsz)}' % t)
    if save_txt or save_img:
        s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
        LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}{s}")
    if update:
        strip_optimizer(weights[0])  # update model (to fix SourceChangeWarning)


def parse_opt():
    parser = argparse.ArgumentParser()
    parser.add_argument('--weights', nargs='+', type=str, default=ROOT / 'yolo-cap.pt', help='model path(s)')
    parser.add_argument('--source', type=str, default=ROOT / 'data/images', help='file/dir/URL/glob/screen/0(webcam)')
    parser.add_argument('--data', type=str, default=ROOT / 'data/coco128.yaml', help='(optional) dataset.yaml path')
    parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[640], help='inference size h,w')
    parser.add_argument('--conf-thres', type=float, default=0.25, help='confidence threshold')
    parser.add_argument('--iou-thres', type=float, default=0.45, help='NMS IoU threshold')
    parser.add_argument('--max-det', type=int, default=1000, help='maximum detections per image')
    parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
    parser.add_argument('--view-img', action='store_true', help='show results')
    parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
    parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
    parser.add_argument('--save-crop', action='store_true', help='save cropped prediction boxes')
    parser.add_argument('--nosave', action='store_true', help='do not save images/videos')
    parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --classes 0, or --classes 0 2 3')
    parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')
    parser.add_argument('--augment', action='store_true', help='augmented inference')
    parser.add_argument('--visualize', action='store_true', help='visualize features')
    parser.add_argument('--update', action='store_true', help='update all models')
    parser.add_argument('--project', default=ROOT / 'runs/predict-cap', help='save results to project/name')
    parser.add_argument('--name', default='exp', help='save results to project/name')
    parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
    parser.add_argument('--line-thickness', default=3, type=int, help='bounding box thickness (pixels)')
    parser.add_argument('--hide-labels', default=False, action='store_true', help='hide labels')
    parser.add_argument('--hide-conf', default=False, action='store_true', help='hide confidences')
    parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference')
    parser.add_argument('--dnn', action='store_true', help='use OpenCV DNN for ONNX inference')
    parser.add_argument('--vid-stride', type=int, default=1, help='video frame-rate stride')
    parser.add_argument('--retina-masks', action='store_true', help='whether to plot masks in native resolution')
    parser.add_argument('--export-mask', action = 'store_true', help = 'export semantic/panoptic masks')
    parser.add_argument('--color-map', type = str, default = ROOT / 'data/color_map.pickle', help = 'color map for semantic/panoptic segmentation, necessary if export mask')
    opt = parser.parse_args()
    opt.imgsz *= 2 if len(opt.imgsz) == 1 else 1  # expand
    print_args(vars(opt))
    return opt


def main(opt):
    check_requirements(exclude=('tensorboard', 'thop'))
    run(**vars(opt))


if __name__ == "__main__":
    opt = parse_opt()
    main(opt)
